<?php
/**
 * File: Authentiate.class.php
 * Author: camy <375766145@qq.com>
 * Time: 2018/3/18 16:51
 */

namespace Common\Extend\Traits;


use Common\Service\User;

trait Authenticate
{
    /**
     * 验证用户
     */
    protected function authenticate()
    {
        $token = cookie('_token');
        if(!$token){
            return false;
        }
        $service = User::instance();
        $user = $service->getUserByAuthKey($token);
        if (!$user) {
            return false;
        }
        //判断过期时间
        $tokenExpireAt = cookie('_token_expire');
        $leftTime = time() - $tokenExpireAt;
        if ($leftTime < 300) {
            //延长token
            $expireTime = C('USER_TOKEN_EXPIRE');
            cookie('_token', $token, ['httponly' => true, 'expire' => $expireTime]);
            cookie('_token_expire', time() + $expireTime, ['httponly' => true, 'expire' => $expireTime]);
        }
        return $user;
    }

}